<template>
  <div class="product-edit-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑商品' : '添加商品' }}</h2>
      <el-button @click="goBack">返回列表</el-button>
    </div>

    <el-form 
      :model="productForm" 
      :rules="rules" 
      ref="productForm" 
      label-width="100px"
      v-loading="loading">
      
      <!-- 基本信息 -->
      <div class="form-section">
        <h3>基本信息</h3>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="productForm.categoryId" placeholder="请选择商品分类">
            <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="productForm.description" :rows="4" placeholder="请输入商品描述"></el-input>
        </el-form-item>
      </div>
      
      <!-- 商品图片 -->
      <div class="form-section">
        <h3>商品图片</h3>
        <el-form-item label="主图" prop="image">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/api/upload"
            :show-file-list="false"
            :on-success="handleMainImageSuccess"
            :before-upload="beforeImageUpload">
            <img v-if="productForm.image" :src="productForm.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="图片集" prop="images">
          <el-upload
            action="http://localhost:8080/api/upload"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleImageSuccess">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </div>
      
      <!-- 销售信息 -->
      <div class="form-section">
        <h3>销售信息</h3>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="productForm.price" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        
        <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="productForm.originalPrice" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" :step="1"></el-input-number>
        </el-form-item>
        
        <el-form-item label="单位" prop="unit">
          <el-input v-model="productForm.unit" placeholder="如: 个、件、箱"></el-input>
        </el-form-item>
        
        <el-form-item label="重量(kg)" prop="weight">
          <el-input-number v-model="productForm.weight" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        
        <el-form-item label="上架状态" prop="status">
          <el-switch
            v-model="productForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="上架"
            inactive-text="下架">
          </el-switch>
        </el-form-item>
      </div>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="submitting">{{ isEdit ? '保存修改' : '立即创建' }}</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getProductDetail, addProduct, updateProduct } from '@/api/product';
import { getCategoryTree } from '@/api/category';

export default {
  name: 'ProductEdit',
  data() {
    return {
      isEdit: false,
      loading: false,
      submitting: false,
      
      // 商品表单
      productForm: {
        id: null,
        merchantId: 1, // 假设当前商家ID为1
        categoryId: null,
        name: '',
        description: '',
        price: 0,
        originalPrice: 0,
        image: '',
        images: '',
        stock: 0,
        sales: 0,
        unit: '',
        weight: 0,
        status: 0
      },
      
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        originalPrice: [
          { required: true, message: '请输入商品原价', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入商品库存', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请上传商品主图', trigger: 'change' }
        ],
        unit: [
          { required: true, message: '请输入商品单位', trigger: 'blur' }
        ]
      },
      
      // 分类列表
      categories: [],
      
      // 图片集相关
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  created() {
    // 获取分类列表
    this.fetchCategories();
    
    // 判断是否为编辑模式
    const productId = this.$route.params.id;
    if (productId) {
      this.isEdit = true;
      this.fetchProductDetail(productId);
    }
  },
  methods: {
    // 获取分类列表
    fetchCategories() {
      getCategoryTree()
        .then(res => {
          if (res.code === 200) {
            this.categories = this.flattenCategories(res.data || []);
          }
        })
        .catch(err => {
          console.error('获取分类失败', err);
          this.$message.error('获取分类失败');
        });
    },
    
    // 扁平化分类树
    flattenCategories(categories, result = []) {
      categories.forEach(category => {
        result.push(category);
        if (category.children && category.children.length > 0) {
          this.flattenCategories(category.children, result);
        }
      });
      return result;
    },
    
    // 获取商品详情
    fetchProductDetail(id) {
      this.loading = true;
      getProductDetail(id)
        .then(res => {
          if (res.code === 200) {
            this.productForm = res.data;
            
            // 处理图片集
            if (this.productForm.images) {
              try {
                const imageArray = JSON.parse(this.productForm.images);
                this.fileList = imageArray.map((url, index) => ({
                  name: `图片${index + 1}`,
                  url
                }));
              } catch (e) {
                console.error('解析图片集失败', e);
              }
            }
          } else {
            this.$message.error(res.message || '获取商品详情失败');
          }
        })
        .catch(err => {
          console.error('获取商品详情失败', err);
          this.$message.error('获取商品详情失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          this.submitting = true;
          
          // 处理图片集
          if (this.fileList.length > 0) {
            const imageUrls = this.fileList.map(file => file.url);
            this.productForm.images = JSON.stringify(imageUrls);
          } else {
            this.productForm.images = '[]';
          }
          
          // 根据编辑状态调用不同API
          const request = this.isEdit ? updateProduct : addProduct;
          request(this.productForm)
            .then(res => {
              if (res.code === 200) {
                this.$message.success(this.isEdit ? '更新成功' : '添加成功');
                this.goBack();
              } else {
                this.$message.error(res.message || (this.isEdit ? '更新失败' : '添加失败'));
              }
            })
            .catch(err => {
              console.error(this.isEdit ? '更新失败' : '添加失败', err);
              this.$message.error(this.isEdit ? '更新失败' : '添加失败');
            })
            .finally(() => {
              this.submitting = false;
            });
        }
      });
    },
    
    // 重置表单
    resetForm() {
      this.$refs.productForm.resetFields();
      if (!this.isEdit) {
        this.fileList = [];
      }
    },
    
    // 返回列表
    goBack() {
      this.$router.push('/merchant/product/list');
    },
    
    // 图片上传前验证
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    
    // 主图上传成功
    handleMainImageSuccess(res) {
      if (res.code === 200) {
        // 修改URL以使用新的文件访问接口
        const originalUrl = res.data;
        // 如果URL是以http://localhost:8080/uploads开头的，转换为/api/files开头
        if (originalUrl.startsWith('http://localhost:8080/uploads/')) {
          this.productForm.image = originalUrl.replace('http://localhost:8080/uploads/', '/api/files/');
        } else {
          this.productForm.image = originalUrl;
        }
      } else {
        this.$message.error(res.message || '上传失败');
      }
    },
    
    // 图片集上传成功
    handleImageSuccess(res, file) {
      if (res.code === 200) {
        // 修改URL以使用新的文件访问接口
        const originalUrl = res.data;
        // 如果URL是以http://localhost:8080/uploads开头的，转换为/api/files开头
        if (originalUrl.startsWith('http://localhost:8080/uploads/')) {
          file.url = originalUrl.replace('http://localhost:8080/uploads/', '/api/files/');
        } else {
          file.url = originalUrl;
        }
      } else {
        this.$message.error(res.message || '上传失败');
      }
    },
    
    // 移除图片
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  }
}
</script>

<style>
.product-edit-container {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.form-section {
  margin-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
}
.form-section h3 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style> 